@file:Suppress("unused")

package com.gitee.ixtf.vertx.handler

import cn.hutool.core.codec.Base58
import cn.hutool.crypto.symmetric.SymmetricCrypto
import com.gitee.ixtf.core.J
import com.gitee.ixtf.core.kotlinx.IxtfEnvString
import io.netty.handler.codec.http.HttpHeaderNames.ETAG
import io.netty.handler.codec.http.HttpHeaderNames.IF_NONE_MATCH
import io.vertx.core.Handler
import io.vertx.ext.web.RoutingContext
import jakarta.inject.Singleton
import java.nio.charset.StandardCharsets.UTF_8

@Singleton
class DlHandler : Handler<RoutingContext> {
  companion object {
    private val key by IxtfEnvString("ixtf.api.dl.key", "ixtf")
    private val alg by IxtfEnvString("ixtf.api.dl.alg", "Blowfish")
    private val crypto by lazy { SymmetricCrypto(alg, key.toByteArray(UTF_8)) }

    fun token(o: Any): String = Base58.encode(crypto.encrypt(o.toString()))

    fun parse(token: String): String = crypto.decryptStr(Base58.decode(token))
  }

  override fun handle(rc: RoutingContext) {
    try {
      if (J.nonBlank(rc.request().headers()[IF_NONE_MATCH])) {
        rc.response().setStatusCode(304).end()
      } else {
        rc.response().putHeader(ETAG, J.objectId()).sendFile(parse(rc.pathParam("token")))
      }
    } catch (t: Throwable) {
      rc.fail(500, t)
    }
  }
}
